package org.boot.easyapi.util.jdbc.mysql;

import lombok.extern.slf4j.Slf4j;
import org.boot.easyapi.util.jdbc.JdbcUtil;
import org.boot.easyapi.pojo.db.DbDTO;
import org.boot.easyapi.pojo.db.TableDTO;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.boot.easyapi.exception.BusinessException.exception;

@Slf4j
public class MysqlAnalyzeUtil {
    /***
     * 获取指定表结构 - mysql
     * @param jdbcTemplate
     * @param table 表名
     * @return
     */
    public static List<TableDTO> analyzeTableBuild(JdbcTemplate jdbcTemplate, String table){
        return jdbcTemplate.execute((ConnectionCallback<List<TableDTO>>) con -> {
            DatabaseMetaData metaData = con.getMetaData();
            List<TableDTO> columnsInfo = new ArrayList<>();
            // 获取所有表名
            ResultSet tables = metaData.getTables(null,  null, table, new String[]{"TABLE"});
            // 检查 DatabaseMetaData 的具体实现类
            while (tables.next())  {
                String tableName = tables.getString("TABLE_NAME");
                // 获取当前表的字段信息
                ResultSet columns = metaData.getColumns(null,  null, tableName, "%");
                while (columns.next())  {
                    TableDTO column = new TableDTO();
                    column.setTable(tableName);
                    column.setType(columns.getString("TYPE_NAME"));
                    column.setSize(columns.getInt("COLUMN_SIZE"));
                    column.setNullable(columns.getInt("NULLABLE")  == DatabaseMetaData.columnNullable);
                    column.setName(columns.getString("COLUMN_NAME"));
                    column.setComment(columns.getString("REMARKS"));
                    columnsInfo.add(column);
                }
            }
            return columnsInfo;
        });
    }


    /**
     * 解析数据库，目前只兼容 mysql
     * @param jdbcTemplate
     * @return
     */
    public static Map<String, List<TableDTO>> analyzeDb(JdbcTemplate jdbcTemplate){
        DbDTO db = JdbcUtil.getDb(jdbcTemplate);
        if(!db.getDbType().toLowerCase().contains("mysql")){
            throw exception("当前数据库不支持全表缓存！");
        }
        //获取数据源中的库模式
        String finalSchema = JdbcUtil.extractCurrentSchema(db.getDbUrl());

        List<TableDTO> result = jdbcTemplate.execute((ConnectionCallback<List<TableDTO>>) con -> {
            DatabaseMetaData metaData = con.getMetaData();
            List<TableDTO> columnsInfo = new ArrayList<>();
            // 获取所有表名
            ResultSet tables = null;
            if(finalSchema != null) metaData.getTables(null,  finalSchema, "%", new String[]{"TABLE"});
            else metaData.getTables(null,  null, "%", new String[]{"TABLE"});
            while (tables.next())  {
                String tableName = tables.getString("TABLE_NAME");
                // 获取当前表的字段信息
                ResultSet columns = metaData.getColumns(null,  null, tableName, "%");
                while (columns.next())  {
                    TableDTO column = new TableDTO();
                    column.setTable(tableName);
                    column.setType(columns.getString("TYPE_NAME"));
                    column.setSize(columns.getInt("COLUMN_SIZE"));
                    column.setNullable(columns.getInt("NULLABLE")  == DatabaseMetaData.columnNullable);
                    column.setName(columns.getString("COLUMN_NAME"));
                    column.setComment(columns.getString("REMARKS")); // 关键改动点
                    columnsInfo.add(column);
                }
            }
            return columnsInfo;
        });
        return result.stream().filter(dto -> dto.getTable() != null).collect(Collectors.groupingBy(TableDTO::getTable));
    }
}
